package com.example.ecommerce.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.ecommerce.dto.LoginRequestDTO;
import com.example.ecommerce.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.stream.Collectors;

@Mapper
public interface UserMapper extends BaseMapper<User> {


    /**
     * 根据用户名查询用户
     */
    default User selectByUsername(String username) {
        return selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getStatus, 1)
                .last("LIMIT 1"));
    }
    
    /**
     * 根据邮箱查询用户
     */
    default User selectByEmail(String email) {
        return selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getEmail, email)
                .eq(User::getStatus, 1)
                .last("LIMIT 1"));
    }
    
    /**
     * 根据手机号查询用户
     */
    default User selectByPhone(String phone) {
        return selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone)
                .eq(User::getStatus, 1)
                .last("LIMIT 1"));
    }
    
    /**
     * 根据角色ID查询用户列表
     */
    default List<User> selectByRoleId(Long roleId) {
        return selectList(new LambdaQueryWrapper<User>()
                .inSql(User::getId, 
                        "SELECT user_id FROM user_roles WHERE role_id = " + roleId + " AND is_deleted = 0")
                .eq(User::getStatus, 1));
    }
    
    /**
     * 查询用户的角色ID列表
     */
    default List<Long> selectRoleIds(Long userId) {
        // 这里使用了子查询，也可以通过XML配置多表关联查询
        return selectObjs(new QueryWrapper<User>()
                .select("role_id")
                .inSql("id", 
                        "SELECT user_id FROM user_roles WHERE user_id = " + userId + " AND is_deleted = 0"))
                .stream()
                .map(obj -> (Long) obj)
                .collect(Collectors.toList());
    }
    
    /**
     * 统计角色下的用户数量
     */
    default Integer countByRoleId(Long roleId) {
        return Math.toIntExact(selectCount(new LambdaQueryWrapper<User>()
                .inSql(User::getId,
                        "SELECT user_id FROM user_roles WHERE role_id = " + roleId + " AND is_deleted = 0")
                .eq(User::getStatus, 1)));
    }
} 